#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>

#define MAX_NUM_INTERVALS 100000


int main(int argc, char **argv) {
  double local, pi, w;
  long N, i;
  double start, end, diff;
  struct timeval t1,
                 t2;

  if (argc < 2) {
  	printf("Usage:\n   %s <num_of_itervals>\n", argv[0]);
	exit(-1);
  }
  
  N = atoi(argv[1]);

  gettimeofday(&t1, NULL);
  
  w = 1.0 / N;
  pi = 0.0;
  for (i = 0; i < N; i++) {
    local = (i + 0.5)*w;
    pi = pi + 4.0/(1.0 + local*local);
  }

  /* Save the end of interval */
  gettimeofday(&t2, NULL);

  /* Calculate process duration */
  start = (double)(t1.tv_sec * 1.0e6) + (double)t1.tv_usec;
  end   = (double)(t2.tv_sec * 1.0e6) + (double)t2.tv_usec;
  diff  = (end - start) / 1.0e6;

  /* Show process time */
  printf("\nTime: %f\n", diff);
  printf("Number of intervals: %d\n", N);
  printf("Calculated Pi: %1.8f\n\n", pi/N);

  return 0;
}
